package com.yuyou.fn.updater.handler;

import com.alibaba.fastjson.JSONArray;
import com.github.wens.mybatisplus.toolkit.StringUtil;
import com.yuyou.fn.common.database.event.EventHandler;
import com.yuyou.fn.common.database.event.IEventHandler;
import com.yuyou.fn.educational.entity.Student;
import com.yuyou.fn.educational.service.IMemberStudentService;
import com.yuyou.fn.educational.service.IStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * @Author: lzh
 * @Date: 2019/4/4
 * 已在新增更新接口同步cid，作废
 */
/*@EventHandler(tables = {"yyfn.student"})
@Component*/
public class StudentToMemberUpdater implements IEventHandler {

    private final Logger log = LoggerFactory.getLogger(StudentToMemberUpdater.class);

    @Resource
    private IMemberStudentService memberStudentService;

    @Resource
    private IStudentService studentService ;


    @Override
    public void insert(String tableName, JSONArray rowList) {
        sendToMember(rowList);
    }

    @Override
    public void update(String tableName, JSONArray rowList, Set<String> updateColumns) {
        if (updateColumns.size()==2 && updateColumns.contains("cid") && updateColumns.contains("update_time") ){
            return;
        }

        sendToMember(rowList);

    }

    /**
     * 发送到会员中心
     * @param rowList
     */
    private void sendToMember(JSONArray rowList) {
        Stream<Student> stream = rowList.toJavaList(Student.class).stream();


        stream.forEach(student -> {

            try{
                doSend(student);
            }catch (Throwable e ){
                //try again
                try{
                    Thread.sleep(TimeUnit.SECONDS.toMillis(1));
                    doSend(student);
                }catch (Throwable e2){
                    log.error("更新cid失败",e2);
                }
            }

        });
    }

    private void doSend(Student student) {
        String memberId = memberStudentService.changeOrNewStudentNew(student);
        if (StringUtil.isNotEmpty(memberId) && !memberId.equalsIgnoreCase(student.getCid())){

            Student update = new Student();
            update.setStudentId(student.getStudentId());
            update.setCid(memberId);
            update.setUpdateTime(new Date());
            studentService.updateSelectiveById(update);
        }
    }

    @Override
    public void delete(String tableName, JSONArray rowList) {

    }

}
